﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.IO;
using MapReduce.Comm.IO;

namespace MapReduce.Comm
{
    public class BaseComm
    {

        protected IOStream mStream;
        public IOStream IOStream
        {
            set {
            mStream = value;
        } }

        public void Close()
        {
            if (mStream!=null) mStream.Close();
        }

        protected byte[] ReceiveData()
        {
            byte[] b = new byte[8];
            mStream.Read(b);
            ulong dataLength = BitConverter.ToUInt64(b, 0);
            b = new byte[dataLength];

            ulong actDataLength = (ulong)mStream.Read(b);
            if (actDataLength != dataLength)
            {
                throw new SystemException("Lengths don't match");
            }

            return b;
        }//ReceiveData


        protected void SendData(byte[] pData)
        {
            if (pData == null) throw new Exception("Null data can not be sent");
            ulong dataLength = (ulong)pData.Length;
            mStream.Write(BitConverter.GetBytes(dataLength));
            mStream.Write(pData);
        }//SendData

 
    }

   


}
